/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.rainbowsheep.reisorg.rest.service.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.rainbowsheep.reisorg.rest.service.model.Country;
import nl.rainbowsheep.reisorg.rest.service.model.Language;
import nl.rainbowsheep.reisorg.rest.service.model.Region;
import nl.rainbowsheep.reisorg.rest.service.model.RegionLocalized;
import nl.rainbowsheep.reisorg.rest.service.repository.RegionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Service class for region
 */
@Service
public class RegionService {

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private LanguageService langService;

    @Autowired
    private CountryService countryService;

    public List<Region> getAllRegions() {
        List<Region> regions = regionRepository.findAll();
        return regions;
    }

    public Region getRegionByName(String name) {
        Region region = regionRepository.findByName(name);
        return region;
    }

    public Region getRegionById(long id) {
        Region region = regionRepository.findById(id);
        return region;
    }

    public List<Region> getAllRegionsByCountry(String country) {
        Country searchedCountry = countryService.getCountryByName(country);
        List<Region> regions = regionRepository.findByCountryId(searchedCountry.getId());
        return regions;
    }

    public List<Region> getAllRegionsByCountryId(Long countryId) {
        List<Region> regions = regionRepository.findByCountryId(countryId);
        return regions;
    }

    public Region save(Region region) {
        Region regionToCheck = getRegionByName(region.getName());
        if (regionToCheck == null) {
//            Country country = getCountryById(region.getCountryId());
            if (region.getCountryId() != 0) {
                Country country = countryService.getCountryById(region.getCountryId());
//                if (country == null) {
//                    country = countryService.getCountryByName(region.getCountry().getName());
//                }
                region.setCountryId(country.getId());
            }
            Map<Language, RegionLocalized> localizedRegionMap = new HashMap<Language, RegionLocalized>();
            region.setLocale(localizedRegionMap);
//            regionToCheck.setLastUpdate(new Date());
            return regionRepository.save(region);
        }
        regionToCheck.setDescription(region.getDescription());
        regionToCheck.setLastUpdate(new Date());

        return regionRepository.save(regionToCheck);
    }
}
